package com.xy.bizportdemo.database;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;

import com.xy.bizportdemo.database.base.DBHelper;
import com.xy.bizportdemo.database.entity.ConversationItem;
import com.xy.bizportdemo.database.entity.MessageItem;
import com.xy.bizportdemo.database.entity.SmsDBTableMessage;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by XIAOYUAN on 2016/11/23.
 */

public class SmsDBManager {
    private static final String TAG = "SmsDBManager";

    private static SmsDBManager sSmsDBManager = null;
    private DBHelper mDBHelper = null;
    private Context mContext = null;

    private SmsDBManager(Context context) {
        mContext = context;
        mDBHelper = SmsDBHelper.getInstance(mContext);
    }

    public void insertBatch(List<ContentValues> list) {
        SQLiteDatabase db = mDBHelper.getDatabase();
        db.beginTransaction();
        for (ContentValues v : list) {
            db.insert(SmsDBTableMessage.NAME, null, v);
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        mContext.getContentResolver().notifyChange(SmsDBHelper.URI_MESSAGE, null);
    }

    public void registerContentObserver(ContentObserver observer) {
        mContext.getContentResolver().registerContentObserver(SmsDBHelper.URI_MESSAGE, true, observer);
    }

    public static SmsDBManager getInstance(Context context) {
        synchronized (SmsDBManager.class) {
            if (sSmsDBManager == null) {
                sSmsDBManager = new SmsDBManager(context);
            }
        }

        return sSmsDBManager;
    }

    public void updateConversationFromMessage() {
        ContentResolver cr = mContext.getContentResolver();
        // get all number in message
        List<String> phoneList = new ArrayList<String>();
        Cursor cursor = cr.query(SmsDBHelper.URI_MESSAGE, new String[]{SmsDBTableMessage.KEY_ADDRESS}, null, null,
                SmsDBTableMessage.KEY_DATE + " desc" + "," + SmsDBTableMessage.KEY_ID + " desc", null);
        if (cursor != null && cursor.moveToFirst()) {
            do {
                String phone = cursor.getString(0);
                if (!TextUtils.isEmpty(phone) && !phoneList.contains(phone)) {
                    phoneList.add(phone);
                }
            } while (cursor.moveToNext());
        }

        if (cursor != null) {
            cursor.close();
        }

        List<ConversationItem> itemList = new ArrayList<ConversationItem>();
        for (String phone : phoneList) {
            int countBlock = 0;
            int countTotal = 0;
            String date = null;
            String body = null;
            //int state = ParseManager.isEnterpriseSms(mContext, phone, null, null) ? ConversationItem.STATE_ENTERPRISE
              //      : ConversationItem.STATE_PERSONAL;
            int state = ConversationItem.STATE_ENTERPRISE;
            cursor = cr.query(SmsDBHelper.URI_MESSAGE, new String[]{SmsDBTableMessage.KEY_DATE, SmsDBTableMessage
                            .KEY_BODY, SmsDBTableMessage.KEY_BLOCK}, SmsDBTableMessage.KEY_ADDRESS + "=?", new
                    String[]{phone},
                    SmsDBTableMessage.KEY_DATE + " desc" + "," + SmsDBTableMessage.KEY_ID + " desc", null);
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    if (date == null) {
                        date = cursor.getString(0);
                    }

                    if (body == null) {
                        body = cursor.getString(1);
                    }

                    if (countTotal == 0) {
                        countTotal = cursor.getCount();
                    }

                    if (cursor.getInt(2) == 1) {
                        countBlock++;
                    }
                } while (cursor.moveToNext());
            }

            if (cursor != null) {
                cursor.close();
            }

            int countNormal = countTotal;
            if (countBlock > 0) {
                itemList.add(new ConversationItem().setNumber(phone).setCount(countBlock).setDate(date)
                        .setBody(body).setState(ConversationItem.STATE_BLOCK));
                countNormal = countTotal - countBlock;
            }

            if (countNormal > 0) {
                itemList.add(new ConversationItem().setNumber(phone).setCount(countNormal).setDate(date)
                        .setBody(body).setState(state));
            }
        }

        // delete all exist conversation
        cr.delete(SmsDBHelper.URI_CONVERSATION, null, null);

        // TODO delete and update
        for (ConversationItem item : itemList) {
            cr.insert(SmsDBHelper.URI_CONVERSATION, item.getContentValues());
        }
    }

    private long writeSms(MessageItem item) {
        long uriId = -1;
        ContentResolver resolver = mContext.getContentResolver();
        Uri uri = resolver.insert(SmsDBHelper.URI_MESSAGE, item.getContentValues());
        if (uri != null) {
            uriId = ContentUris.parseId(uri);
        }

        return uriId;
    }

    public long writeSmsToInBox(String phoneNum, String msgBody) {
        MessageItem item = new MessageItem().setAddress(phoneNum).setBody(msgBody).setType(MessageItem
                .MESSAGE_TYPE_INBOX);
        return writeSms(item);
    }

    public long writeSmsToSentBox(String phoneNum, String msgBody) {
        MessageItem item = new MessageItem().setAddress(phoneNum).setBody(msgBody).setType(MessageItem
                .MESSAGE_TYPE_OUTBOX);
        return writeSms(item);
    }

}
